<!-- pay.html -->
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title data-i18n="payTitle">支付定金</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    * { 
      box-sizing: border-box; 
      margin: 0; 
      padding: 0; }
    body { 
      font-family: Arial, sans-serif; 
      background-color: #007bff;
      margin: 0; 
      padding: 15px; }
    .back-btn {
      background: #eee;
      border: none;
      padding: 8px 12px;
      border-radius: 6px;
      font-size: 14px;
      cursor: pointer;
      margin-bottom: 15px;
    }
    .back-btn:hover { background: #ddd; }
    .container {
      max-width: 600px;
      margin: 0 auto;
      background: #fff;
      padding: 30px;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      text-align: center;
    }
    h1 { font-size: 24px; margin-bottom: 20px; color: #333; }
    .order-summary { font-size: 16px; margin-bottom: 20px; line-height: 1.6; text-align: left; }
    .order-summary p { margin: 8px 0; }
    #paypal-button-container { margin-top: 20px; max-width: 350px; margin-left: auto; margin-right: auto; }
    .divider {
      margin: 30px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #888;
    }
    .divider::before,
    .divider::after {
      content: "";
      flex: 1;
      height: 1px;
      background: #ccc;
      margin: 0 10px;
    }
    .qr-section { margin-top: 30px; }
    .qr-section h2 { font-size: 20px; margin-bottom: 15px; color: #333; }
    .qr-container {
      display: flex;
      justify-content: center;
      gap: 20px;
      flex-wrap: wrap;
    }
    .qr-box { text-align: center; }
    .qr-box img {
      width: 150px;
      height: 150px;
      border: 1px solid #ccc;
      border-radius: 10px;
    }
    .qr-box.promptpay img {
      width: 150px;
      height: auto;
    }
    .qr-box p { font-size: 16px; margin-top: 8px; color: #444; }
    .proof-link {
      display: inline-block;
      margin-top: 20px;
      background: #007bff;
      color: #fff;
      padding: 10px 16px;
      border-radius: 8px;
      text-decoration: none;
      font-size: 16px;
    }
    .proof-link:hover { background: #0056b3; }
    footer { margin-top: 30px; font-size: 14px; color: #999; }
  </style>  
  
</head>
<body>
  <button class="back-btn" onclick="goBack()">← <span data-i18n="uploadPaymentBack">返回</span></button>

  <div class="container">
    <h1 data-i18n="payTitle">支付定金</h1>
    <!-- 订单摘要区域，订单信息将在脚本中填充 -->
    <div class="order-summary" id="orderSummary">
      <span data-i18n="payTotalLabel">定金金额：</span>
      <strong id="depositValue">฿500</strong>
    </div>
    <div id="paypal-button-container"></div>

    <!-- PayPal 按钮容器 -->
    <div class="divider" data-i18n="dividerOr">或</div>

        <!-- 二维码支付区域 -->
        <div class="qr-section">
          <h2 data-i18n="payUploadTitle">上传支付凭证</h2>
          <div class="qr-container">
            <div class="qr-box">
              <img src="https://github.com/Anquanchehang/rental/blob/main/WechatIMG16118.jpg?raw=true" alt="二维码">
              <p data-i18n="aliPayLabel">支付宝支付</p>
            </div>
            <div class="qr-box">
              <img src="https://github.com/Anquanchehang/rental/blob/main/WechatIMG16117.jpg?raw=true" alt="二维码">
              <p data-i18n="weChatLabel">微信支付</p>
            </div>
            <div class="qr-box promptpay">
              <img src="https://github.com/Anquanchehang/rental/blob/main/WechatIMG16119.jpg?raw=true" alt="PromptPay QR">
              <p data-i18n="promptpayLabel">PromptPay</p>
            </div>
          </div>
          <p style="margin-top: 15px;" data-i18n="qrInstruction">请使用相应 App 扫描二维码完成支付</p>
          <!-- 上传支付凭证链接，初始 href 为 upload.html，后面会追加 orderId -->
          <a class="proof-link" id="uploadProofLink" href="upload.html" data-i18n="payUploadTitle">上传支付凭证</a>
        </div>
      </div>
      <script src="https://www.paypal.com/sdk/js?client-id=ASsijEO47xH4dc0k0PMnnnd3EBwMALhqhyd-cxWreY4wWHHPb2TJ7t11QmVAy8SJXTe0VyFsVqJcbwop&currency=THB"></script>
      <script>
        function goBack() {
          window.history.back();
        }
    
        // 初始化 PayPal 按钮
        paypal.Buttons({
          createOrder: function(data, actions) {
            return actions.order.create({
              purchase_units: [{
                amount: { value: '500.00' },
                description: "租车订单定金"
              }]
            });
          },
          onApprove: function(data, actions) {
            return actions.order.capture().then(function(details) {
              // 支付成功后直接跳转到成功页面（success.html）
              window.location.href = "success.html?orderId=ABC123"; // 可传订单号参数
            });
          },
          onError: function(err) {
            console.error("PayPal 支付错误：", err);
            alert("支付过程中出现错误，请稍后重试");
          }
        }).render('#paypal-button-container');
      </script>
  <!-- PayPal SDK -->
  <script type="module">
    async function loadLanguage(lang) {
      try {
        const resp = await fetch(`lang/${lang}.json`);
        return await resp.json();
      } catch (err) {
        console.error("语言文件加载失败:", err);
        return {};
      }
    }
    function applyLanguage(langData) {
      document.querySelectorAll("[data-i18n]").forEach(el => {
        const key = el.getAttribute("data-i18n");
        if (langData[key]) {
          el.textContent = langData[key];
        }
      });
      document.querySelectorAll("[data-i18n-placeholder]").forEach(el => {
        const key = el.getAttribute("data-i18n-placeholder");
        if (langData[key]) {
          el.setAttribute("placeholder", langData[key]);
        }
      });
    }
    function getCurrentLang() {
      return localStorage.getItem("selectedLanguage") || "zh";
    }
    let currentLangData = {};
    async function initLanguage() {
      const currentLang = getCurrentLang();
      currentLangData = await loadLanguage(currentLang);
      applyLanguage(currentLangData);
    }
    window.addEventListener("DOMContentLoaded", async () => {
      await initLanguage();
    });


    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-app.js";
    import { getFirestore, doc, getDoc } from "https://www.gstatic.com/firebasejs/9.22.2/firebase-firestore.js";

    const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "rental-7fe8c.firebaseapp.com",
    projectId: "rental-7fe8c",
    storageBucket: "rental-7fe8c.firebasestorage.app",
    messagingSenderId: "263132536954",
    appId: "1:263132536954:web:55d988d88b1a078b4b9bc3",
  };
    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);


    // 读取 URL 参数
    const params = new URLSearchParams(window.location.search);
    const orderId = params.get("orderId");  // 这是 docRef.id

    // 如果有 orderId，就去 Firestore 查询
    if (orderId) {
      console.log("pay.html 拿到 orderId =", orderId);
      const orderDocRef = doc(db, "orders", orderId);
      getDoc(orderDocRef).then(docSnap => {
        if (docSnap.exists()) {
          const orderData = docSnap.data();
          console.log("pay.html 查询到订单:", orderData);

          // 显示到页面上
          
          applyLanguage(currentLangData);

          // 给 “上传支付凭证” 的按钮加上链接
          // 注意带上 docRef.id
          document.getElementById("uploadProofLink").href = "upload.html?orderId=" + orderId;

        } else {
          document.getElementById("orderSummary").textContent = "未找到该订单文档！";
        }
      }).catch(err => {
        console.error("查询订单失败:", err);
        document.getElementById("orderSummary").textContent = "加载订单失败，请稍后重试。";
      });
    } else {
      document.getElementById("orderSummary").textContent = "没有传入 orderId";
    }
  
  </script>
</body>
</html>